import { prisma } from '@/lib/prisma';
import NavCategoryContentClient from '@/components/NavCategoryContentClient';
import { SidebarServer } from '@/components/SidebarServer';
import { unstable_noStore as noStore } from 'next/cache'

type NavCategoryContentProps = {
  sysCode?: string;
};

export default async function NavCategoryContent({ sysCode = 'kason_nav' }: NavCategoryContentProps) {
  // 禁用该服务端组件的缓存，每次请求实时读取数据库
  noStore()

  const nav = await prisma.menu.findFirst({
    where: { sysCode, isActive: 1 },
    include: { categories: true },
  });

  const groupedContents: Record<string, any[]> = {};

  if (nav) {
    nav.categories.forEach((c) => (groupedContents[c.id] = []));

    const items = await prisma.content.findMany({
      where: {
        categories: {
          some: {
            category: { menuId: nav.id },
          },
        },
      },
      orderBy: { createdAt: 'desc' },
      take: 1000,
      include: {
        categories: { include: { category: true } },
        cover: true,
      },
    });

    const normalized = items.map((item) => ({
      ...item,
      categories: item.categories.map((cc) => cc.category),
      createdAt: item.createdAt.toISOString(),
      updatedAt: item.updatedAt.toISOString(),
    }));

    for (const content of normalized) {
      for (const c of content.categories) {
        if (groupedContents[c.id]) {
          groupedContents[c.id].push(content);
        }
      }
    }
  }

  return (
    <div className="flex flex-1 min-h-[calc(100vh-4rem)]">
      {nav ? <SidebarServer categories={nav.categories} /> : null}
      <NavCategoryContentClient sysCode={sysCode} nav={nav as any} groupedContents={groupedContents as any} />
    </div>
  );
}